package com.sansan.qiangji.controller.system;

import com.sansan.qiangji.VO.system.role.RoleVO;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.system.role.RoleMenuPowerEditForm;
import com.sansan.qiangji.realize.system.RoleReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController {
    private RoleReal roleReal;

    @Resource
    public void setRoleReal(RoleReal roleReal){
        this.roleReal= roleReal;
    }

    @PostMapping("/create")
    public ResultVO<Object> createRole(@RequestParam(name = "roleName") String roleName) {
        roleReal.createRole(roleName);
        return ResultVOUtil.success(null);
    }

    @GetMapping("/list")
    public ResultVO<Object> getRoles() {
        List<RoleVO> roleVOS = roleReal.getRoles();
        return ResultVOUtil.success(roleVOS);
    }

    @PostMapping("/delete")
    public ResultVO<Object> deleteRole(@RequestParam(name = "roleId") Integer roleId) {
        roleReal.deleteRole(roleId);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/changeStatus")
    public ResultVO<Object> changeRoleStatus(@RequestParam(name = "roleId") Integer roleId) {
        roleReal.changeRoleStatus(roleId);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/roleMenuPowerEdit")
    public ResultVO<Object> roleMenuPowerEdit(@Valid @RequestBody RoleMenuPowerEditForm roleMenuPowerEditForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【角色菜单权限编辑】参数不正确，roleMenuPowerEditForm={}", roleMenuPowerEditForm.toString());
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        roleReal.roleMenuPowerEdit(roleMenuPowerEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/rolePowerEdit")
    public ResultVO<Object> rolePowerEdit(@RequestParam(name = "roleId") Integer roleId, @RequestParam(name = "powerName") String powerName) {
        roleReal.rolePowerEdit(roleId, powerName);
        return ResultVOUtil.success(null);
    }
}
